<?php
namespace app\home\logic;

use think\Model;

class Charge extends Model {
    public function charge($data = []) {
        if (!isset($data['payment'])) {
            return ['code' => 0, 'msg' => '请选择充值方式'];
        }
        if (!isset($data['money']) || $data['money'] <= 0) {
            return ['code' => 0, 'msg' => '充值金额必须大于0'];
        }
        if (!isset($data['user_id'])) {
            return ['code' => 0, 'msg' => '用户ID不能为空'];
        }
        $payment = model('account_payment')->getOne(['id' => $data['payment'], 'status' => 1, 'from' => 2]);
        if (!$payment) {
            return ['code' => 0, 'msg' => '支付方式不存在'];
        }
        $user_bank = model('account_users_bank')->getOne(['user_id' => $data['user_id']]);
        if (!$user_bank) {
            return ['code' => 0, 'msg' => '请先绑定银行卡'];
        }

        $payment_class = model($payment['nid'], 'logic');

        $order_id = $data['user_id'] . time() . rand(1000, 9999);
        $recharge_data['money'] = $data['money'];
        $recharge_data['payment'] = $data['payment'];
        $recharge_data['user_id'] = $data['user_id'];
        $recharge_data['status'] = 0;
        $recharge_data['type'] = isset($payment_class->type) ? $payment_class->type : 1;
        $recharge_data['remark'] = "在线充值(" . $payment['nid'] . ")";
        $recharge_data['nid'] = $order_id;
        model('account_recharge')->add($recharge_data); //添加充值订单，返回ID号

        $user = model('user')->getUser(['user_id' => $data['user_id']]);

        $result = $payment_class->submit([
                'order_id' => $order_id,//订单号;
                'login_id' => $user['username'],
                'money' => $data['money'],
        ]);
        return $result;
    }

    public function callback($data = []) {
        $result = model($data['payment'], 'logic')->callback($data);
        return $result;
    }

    /**
     * 充值审核
     *
     * @param Array $data =array("nid"=>"订单号","verify_remark"=>"审核备注","status"=>"审核状态")
     * @return Boolen
     */
    static function VerifyRecharge($data = []) {
        //判断订单号是否存在
        if (!isset($data['nid'])) {
            return false;
        }
        $prefix = config('database.prefix');

        $sql = "select p1.*,p2.username,p3.name as payment_name from `{$prefix}account_recharge` as p1 left join `{$prefix}users` as p2 on p1.user_id=p2.user_id left join `{$prefix}account_payment` as p3 on p1.payment=p3.nid where p1.`nid`='{$data['nid']}'";
        $re = db()->query($sql);
        if (!$re) {
            return false;
        }
        $result = $re[0];

        $recharge_userid = $result['user_id'];//充值用户id
        $recharge_nid = $result['nid'];//充值编号
        $recharge_money = $result['money'];//充值总额
        $recharge_addjl = $result['addjl'];//充值奖励
        $recharge_fee = $result['fee'];//费用
        $recharge_balance = $result['balance'];//余额
        $username = $result['username'];//用户名
        $payment = $result['payment_name'];//用户名
        $type2 = $result['type'];//用户名
        $actual_money = $result['money'];//实际到账金额

        $id = $result['id'];

        $num = db('account_recharge')->where(['nid' => $data['nid']])->count();
        //判断订单号是否有误
        if ($num > 1) {
            return false;
        }
        if ($data['status'] == 1) {
            if ($type2 == 2) {
                $log_info["user_id"] = $recharge_userid;//操作用户id
                $log_info["nid"] = "recharge_fee_" . $data['nid'];//订单号
                $log_info["account_web_status"] = 1;//
                $log_info["account_user_status"] = 1;//
                $log_info["code"] = "account";//
                $log_info["code_type"] = "recharge_success";//
                $log_info["code_nid"] = $data['nid'];//
                $log_info["money"] = $recharge_money;//操作金额
                $log_info["income"] = $log_info["money"];//收入
                $log_info["expend"] = 0;//支出
                $log_info["balance_cash"] = $log_info["money"];//可提现金额
                $log_info["balance_frost"] = 0;//不可提现金额
                $log_info["frost"] = 0;//冻结金额
                $log_info["await"] = 0;//待收金额
                $log_info["repay"] = 0;//待还金额
                $log_info["type"] = "recharge";//类型
                $log_info["to_userid"] = 0;//付给谁
                $log_info["remark"] = "后台充值{$recharge_money}元成功";//备注
                $result = model('account', 'logic')->AddLog($log_info);
                if (!$result['code']) {
                    return false;
                }
            } else {
                $log_info["user_id"] = $recharge_userid;//操作用户id
                $log_info["nid"] = "recharge_" . $data['nid'];//订单号
                $log_info["account_web_status"] = 0;//
                $log_info["account_user_status"] = 1;//
                $log_info["code"] = "account";//
                $log_info["code_type"] = "recharge_success";//
                $log_info["code_nid"] = $data['nid'];//
                $log_info["money"] = $recharge_money;//操作金额
                $log_info["income"] = $log_info["money"];//收入
                $log_info["expend"] = 0;//支出
                $log_info["balance_cash"] = 0;//可提现金额
                $log_info["balance_frost"] = $log_info["money"];//不可提现金额
                $log_info["frost"] = 0;//冻结金额
                $log_info["await"] = 0;//待收金额
                $log_info["repay"] = 0;//待还金额
                $log_info["type"] = "recharge";//类型
                $log_info["to_userid"] = 0;//付给谁
                $log_info["remark"] = "通过{$payment}充值了{$recharge_money}元";//备注
                $result = model('account', 'logic')->AddLog($log_info);
                if (!$result['code']) {
                    return false;
                }
                if ($recharge_addjl > 0) {
                    $log_info["user_id"] = $recharge_userid;//操作用户id
                    $log_info["nid"] = "recharge_fee_" . $data['nid'];//订单号
                    $log_info["account_web_status"] = 1;//
                    $log_info["account_user_status"] = 1;//
                    $log_info["code"] = "account";//
                    $log_info["code_type"] = "recharge_success";//
                    $log_info["code_nid"] = $data['nid'];//
                    $log_info["money"] = $recharge_addjl;//操作金额
                    $log_info["income"] = $log_info["money"];//收入
                    $log_info["expend"] = 0;//支出
                    $log_info["balance_cash"] = 0;//可提现金额
                    $log_info["balance_frost"] = $log_info["money"];//不可提现金额
                    $log_info["frost"] = 0;//冻结金额
                    $log_info["await"] = 0;//待收金额
                    $log_info["repay"] = 0;//还款费用
                    $log_info["type"] = "addjl";//类型
                    $log_info["to_userid"] = 0;//付给谁
                    $log_info["remark"] = "单号【{$recharge_nid}】充值成功奖励{$recharge_addjl}元";//备注
                    $result = model('account', 'logic')->AddLog($log_info);
                    if (!$result['code']) {
                        return false;
                    }
                } else if ($recharge_addjl < 0) {
                    $recharge_addjl = abs($recharge_addjl);
                    $log_info["user_id"] = $recharge_userid;//操作用户id
                    $log_info["nid"] = "recharge_fee_" . $data['nid'];//订单号
                    $log_info["account_web_status"] = 1;//
                    $log_info["account_user_status"] = 1;//
                    $log_info["code"] = "account";//
                    $log_info["code_type"] = "recharge_success";//
                    $log_info["code_nid"] = $data['nid'];//
                    $log_info["money"] = $recharge_addjl;//操作金额
                    $log_info["income"] = 0;//收入
                    $log_info["expend"] = $log_info["money"];//支出
                    $log_info["balance_cash"] = 0; //可提现金额
                    $log_info["balance_frost"] = $log_info["money"];//不可提现金额
                    $log_info["frost"] = 0;//冻结金额
                    $log_info["await"] = 0;//待收金额
                    $log_info["repay"] = 0;//还款费用
                    $log_info["type"] = "addjl";//类型
                    $log_info["to_userid"] = 0;//付给谁
                    $log_info["remark"] = "单号【{$recharge_nid}】充值成功奖励{$recharge_addjl}元";//备注
                    $result = model('account', 'logic')->AddLog($log_info);
                    if (!$result['code']) {
                        return false;
                    }
                }
                if ($recharge_fee > 0) {
                    $log_info["user_id"] = $recharge_userid;//操作用户id
                    $log_info["nid"] = "recharge_fee_" . $data['nid'];//订单号
                    $log_info["account_web_status"] = 1;//
                    $log_info["account_user_status"] = 1;//
                    $log_info["code"] = "account";//
                    $log_info["code_type"] = "recharge_offline_fee";//
                    $log_info["code_nid"] = $data['nid'];//
                    $log_info["money"] = $recharge_fee;//操作金额
                    $log_info["income"] = 0;//收入
                    $log_info["expend"] = $log_info["money"];//支出
                    $log_info["balance_cash"] = 0;//可提现金额
                    $log_info["balance_frost"] = -$log_info["money"];//不可提现金额
                    $log_info["frost"] = 0;//冻结金额
                    $log_info["await"] = 0;//待收金额
                    $log_info["repay"] = 0;//还款费用
                    $log_info["type"] = "recharge_fee";//类型
                    $log_info["to_userid"] = 0;//付给谁
                    $log_info["remark"] = "单号【{$recharge_nid}】充值成功扣除{$recharge_fee}元手续费";//备注
                    $result = model('account', 'logic')->AddLog($log_info);
                    if (!$result['code']) {
                        return false;
                    }
                } else if ($recharge_fee < 0) {
                    $recharge_fee = abs($recharge_fee);
                    $log_info["user_id"] = $recharge_userid;//操作用户id
                    $log_info["nid"] = "recharge_fee_" . $data['nid'];//订单号
                    $log_info["account_web_status"] = 1;//
                    $log_info["account_user_status"] = 1;//
                    $log_info["code"] = "account";//
                    $log_info["code_type"] = "recharge_offline_fee";//
                    $log_info["code_nid"] = $data['nid'];//
                    $log_info["money"] = $recharge_fee;//操作金额
                    $log_info["income"] = $log_info["money"];//收入
                    $log_info["expend"] = 0;//支出
                    $log_info["balance_cash"] = 0; //可提现金额
                    $log_info["balance_frost"] = $log_info["money"];//不可提现金额
                    $log_info["frost"] = 0;//冻结金额
                    $log_info["await"] = 0;//待收金额
                    $log_info["repay"] = 0;//还款费用
                    $log_info["type"] = "recharge_fee";//类型
                    $log_info["to_userid"] = 0;//付给谁
                    $log_info["remark"] = "单号【{$recharge_nid}】线下充值成功奖励{$recharge_fee}元";//备注
                    $result = model('account', 'logic')->AddLog($log_info);
                    if (!$result['code']) {
                        return false;
                    }
                }
            }
            //加入用户操作记录
            $user_log["user_id"] = $recharge_userid;
            $user_log["code"] = "account";
            $user_log["type"] = "recharge";
            $user_log["operating"] = "success";
            $user_log["article_id"] = $data['nid'];
            $user_log["result"] = 1;
            $user_log["content"] = '用户' . $username . '在' . date("Y-m-d H:i:s") . $log_info["remark"];
            $result = model('users_log')->AddUsersLog($user_log);
            if (!$result) {
                return false;
            }

            //充值成功站内信提醒
            $remind['nid'] = "recharge_success";
            $remind['receive_userid'] = $recharge_userid;
            $remind['remind_nid'] = "recharge_success_" . $recharge_userid . "_" . $data['nid'];
            $remind['code'] = "account";
            $remind['article_id'] = $recharge_userid;
            $remind['title'] = "充值成功";
            $remind['content'] = "充值" . $recharge_money . "成功。";
            model('remind', 'logic')->sendRemind($remind);

        } else {
            //充值失败站内信提醒
            $remind['nid'] = "recharge_false";
            $remind['receive_userid'] = $recharge_userid;
            $remind['remind_nid'] = "recharge_false_" . $recharge_userid . "_" . $data['nid'];
            $remind['code'] = "account";
            $remind['article_id'] = $recharge_userid;
            $remind['title'] = "充值失败";
            $remind['content'] = "充值" . $recharge_money . "审核不通过。失败原因：{$data['verify_remark']}";
            model('remind', 'logic')->sendRemind($remind);
        }
        return $id;
    }

    function OnlineReturnNo($data = []) {
        $trade_no = $data['trade_no'];
        if (!$trade_no) {
            return null;
        }
        model('account_recharge')->edit(['nid' => $trade_no, 'status' => 0], ['status' => 2, 'return' => serialize(input()), 'verify_remark' => $data['verify_remark'], 'sign' => $data['sign']]);
    }

    //在线充值返回数据处理
    function OnlineReturn($data = []) {
        $trade_no = $data['trade_no'];
        $rechage_result = model('account_recharge')->getOne(["nid" => $trade_no]);
        if ($rechage_result && ($rechage_result['status'] == 0 || $rechage_result['status'] == 2)) {
            $re = model('account_recharge')->edit(['nid' => $trade_no, 'status' => ['in', '0,2']], ['status' => 1, 'return' => serialize(input()), 'verify_userid' => 0, 'balance' => $rechage_result['money'], 'verify_remark' => '成功充值', 'sign' => isset($data['sign']) ? $data['sign'] : '']);
            if (!$re) {
                return false;
            }

            $result = model('account_log')->getOne(['user_id' => $rechage_result['user_id'], 'nid' => $trade_no]);
            if (!$result) {
                $credit_log['user_id'] = $rechage_result['user_id'];
                $credit_log['nid'] = "online_recharge";
                $credit_log['code'] = "account";
                $credit_log['type'] = "recharge_approve";
                $credit_log['addtime'] = time();
                $credit_log['article_id'] = $result['id'];
                $credit_log['remark'] = "用户在线充值所得的积分";
                model('credit', 'logic')->ActionCreditLog($credit_log);

                $rec['nid'] = $rechage_result['nid'];
                $rec['return'] = serialize(input());
                $rec['status'] = 1;
                $rec['verify_userid'] = 0;
                $rec['verify_time'] = time();
                $rec['verify_remark'] = "成功充值";

                $result = self::VerifyRecharge($rec);
                if (!$result) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

}